import * as userApi from '@/api/user';

export default {
  namespaced: true,
  state: {
    // 登录状态
    loading: false,
    // 检查登录用户
    checking: false,
  },
  getters: {
    status(state, getters, rootState) {
      if (state.checking) return 'checking';
      if (
        rootState.userInfo.username
        && rootState.userInfo.email
        && rootState.userInfo.appkey
      ) return 'login';
      return 'unlogin';
    },
  },
  mutations: {
    setLoading(state, loading) {
      state.loading = loading;
    },
    setChecking(state, checking) {
      state.checking = checking;
    },
  },
  actions: {
    async login({ commit }, userInfo) {
      commit('setLoading', true);
      const user = await userApi.login(userInfo);
      if (user) commit('userInfo/setUserInfo', user, { root: true });
      commit('setLoading', false);
      return user;
    },
    async whoAmI({ commit }) {
      commit('setChecking', true);
      const user = await userApi.whoAmI();
      if (user) commit('userInfo/setUserInfo', user, { root: true });
      commit('setChecking', false);
    },
    async loginOut({ commit }) {
      commit('setChecking', true);
      await userApi.loginOut();
      commit('userInfo/setUserInfo', {
        username: '',
        email: '',
        appkey: '',
        role: '',
      }, { root: true });
      commit('setChecking', false);
    },
  },
};
